/**
 * Created by HeartFul on 2014/8/14.
 */
var menu = function () {
    $(".dt_warp").remove();
    LeftTime = 1;
    canRefresh =false;

    var dt_warp = d3.select("body").append("div").classed("dt_warp", true).style({
        height: "100%",
        "overflow": "hidden"
    });
    var index_bg = dt_warp.append("div").classed("index_bg", true).style({
        height: "100%",
        background: 'url(../../common/page/images/sy_bg.jpg) no-repeat top center',
        "overflow": "hidden",
        "background-size": "100%"
    });
    var datong_header = index_bg.append("div").classed("datong_header", true);
    datong_header.append("h1").html("我的应用");
    index_bg.append("div").classed("item_list", true).classed("one", true).style({
        position: 'relative', 'z-index': 10, top: '0px', padding: '0px', left: '0px', height: '77%'
    }).attr("id", "oneList");
    var footer = index_bg.append("div").classed("footer", true).style({
        position: 'absolute', bottom: '0px'
    });
    footer.append("div").classed("f_navone", true).attr("type", "button").append("span");
    footer.append("div").classed("f_navtwo", true).attr("type", "button");
    footer.append("div").classed("f_navthree_click", true).attr("type", "button");
    footer.append("div").classed("f_navfour", true).attr("type", "button");
    $(".f_navone").hammer().on(touch_s, function () {
        task();
    });
    $(".f_navtwo").hammer().on(touch_s, function () {
        tzzx();
    });
    $(".f_navfour").hammer().on(touch_s, function () {
        zhgl();
    });


    onMenu();
};
var onMenu = function () {
    d3.select("body").append("div").classed("shadow", true).style({
        position: "absolute",
        left: "0px",
        top: "0px",
        width: "320px",
        height: "400px",
        opacity: "0",
        "z-index": "99"
    });
    //  init();
    if (window.localStorage.task && window.localStorage.task != "0") {
        d3.select(".f_navone span").html(window.localStorage.task).style({
            "opacity": 1
        });
        if (window.localStorage.task.length >= 3)
            d3.select(".f_navone span").html("99+")
                .style({
                    "opacity": 1,
                    "width": "30px"
                });
    }

    else {
        d3.select(".f_navone span").remove();
    }

    var url = serverURL + "cmcp/app/findAllInstalledMBApps.json";
    setInterval(function () {
        if (window.localStorage.appStatu == "true") {
            window.localStorage.appStatu = "false";
            var xtechAth=window.localStorage["xtechAth"];
            $.ajax({
                url: url, //"test.json",
                beforeSend: function(xhr) {
                	xhr.setRequestHeader("XTECH_ATH",xtechAth);
                },
                dataType: "text",
                success: function (r) {
                    if (typeof (r) == "string") {
                        r = JSON.parse(r);
                    }
                    List = r;

                    console.log("List", List);
                    var yyzx = {
                        appCode: "应用中心",
                        appURL: "yyzx",
                        appImgUrl: "yyzx.png",
                        img: "yyzx",
                        id: 10000,
                        sort: 111111,
                        position: "mbdesk1"
                    };
                    List.list.push(yyzx);
                    window.localStorage.Lcatch = JSON.stringify(r);
                    draw(List);
                },
                error: function (e) {
                    List = JSON.parse(window.localStorage.Lcatch);
                    console.log("List", List);


                    draw(List);

                    console.log("erro");
                }
            });
        }
    }, 1500);
    if (true) {
    	var xtechAth=window.localStorage["xtechAth"];
        $.ajax({
            url: url, //"test.json",
            dataType: "text",
            beforeSend: function(xhr) {
            	xhr.setRequestHeader("XTECH_ATH",xtechAth);
            },
            success: function (r) {
                if (typeof (r) == "string") {
                    r = JSON.parse(r);
                }
                List = r;

                console.log("List", List);
                var yyzx = {
                    appCode: "应用中心",
                    appURL: "yyzx",
                    appImgUrl: "yyzx.png",
                    img: "yyzx",
                    id: 10000,
                    sort: 111111,
                    position: "mbdesk1"
                };
                List.list.push(yyzx);
                window.localStorage.Lcatch = JSON.stringify(r);
                draw(List);
                //              console.log(window.localStorage.Lcatch);
            },
            error: function (e) {
                //   alert("error");
                List = JSON.parse(window.localStorage.Lcatch);

                console.log("List", List);


                draw(List);

                console.log("erro");
            }
        });
    } else {

        List = JSON.parse(window.localStorage.Lcatch);


        var yyzx = {
            appCode: "应用中心",
            appURL: "yyzx",
            appImgUrl: "yyzx.png",
            img: "yyzx",
            id: 10000,
            sort: 111111,
            position: "mbdesk1"
        };
        List.list.push(yyzx);
        draw(List);

    }

    function draw(list) {

        setTimeout(function () {
            d3.selectAll(".shadow").remove();
        }, 250);


        var mostLeft = Math.floor(list.list.length / 12) + 1;
        d3.select(".one ul").remove();
        //  d3.select(".index_btm ul").remove();

        var W = d3.select(".one").style("width");
        var W1 = width
        W = +W.substr(0, W.length - 2) * 0.25;
        var H = d3.select(".one").style("height");
        H = +H.substr(0, H.length - 2) * 0.24;
        var ul = d3.select(".one").append("ul").style({
            position: "absolute",
            left: "0px"
        }).classed("ul1", true);
        /*
         var ul2 = d3.select(".one").append("ul").style({
         position: "absolute",
         left: width + "px"
         }).classed("ul2", true);

         var ul3 = d3.select(".one").append("ul").style({
         position: "absolute",
         left: 2 * width + "px"
         }).classed("ul3", true);

         var ul4 = d3.select(".one").append("ul").style({
         position: "absolute",
         left: 3 * width + "px"
         }).classed("ul4", true);

         var ul4 = d3.select(".one").append("ul").style({
         position: "absolute",
         left: 4 * width + "px"
         }).classed("ul5", true);
         for (var i = 2; i <= mostLeft; i++) {
         Deskpend(i, list);
         }
         Hammer(".one").on("swipe", function (e) {
         e.preventDefault();
         if (e.gesture && e.gesture.direction) {
         Appstore(e.gesture.direction, LeftTime, mostLeft);
         }
         });
         */
        var ul_ = d3.select(".index_btm ul");
        for (var i = 0, j = 0, k = 0; i < list["list"].length; i++) {
            if (list["list"][i].position) {
                var li = ul.append("li").classed("li", true).attr("data-index", list["list"][i].id)
                    .attr("data-url", list["list"][i].appURL)
					.attr("data-appVersion", list["list"][i].appVersion)
                    .attr("data-key", i).style({
                        "position": "absolute",
                        left: (k % 4) * W + "px",
                        top: Math.floor(k / 4) * H + 20 + "px"

                    }).attr("x", (k % 4) * W).attr("y", Math.floor(k / 4) * H + 20);
                var x = li.append("p").style({
                    width: W + "px"
                    //     height:W+"px"
                });
				if(list["list"][i]["appVersion"] == "oacloud"){
					var imgURL=list["list"][i]["wholeImgUrl"].substr(1,list["list"][i]["wholeImgUrl"].length);
					x.html("<img src="+serverURL+imgURL+" width=50% height=auto>").append("br");
				}else{
					var imgURL = list["list"][i]["appImgUrl"].split(".")[0];
					x.html("<img src=../../common/page/images/" + imgURL+ "D.png width=50% height=auto>").append("br");
				}
                x.append("span").html(list["list"][i].appCode);
//
                k++;
                continue;
            }
        }
       // var oneScroll = new iScroll("oneList", {hScrollbar: false, vScrollbar: false});
        drag();
        function drag() {
            $(".one ul .li").hammer().on("hold", function (e) {
                $(this).data("edit", true).data("scale", 1.07).data("hold", true);
                d3.selectAll(".one ul li p img").transition().duration(250).style("-webkit-transform", "scale(1.05)");
                d3.selectAll(".one ul li p span").transition().duration(250).style("-webkit-transform", "scale(1.05)");
                return;
            });
            $(".one ul .li").hammer().on("dragstart", function (e) {
                e.preventDefault();
                if ($(this).data("hold")) {
                    $(this).css("z-index", 111);
                    $(".one").css("border", "1px solid #aaa");
                    delappend();
                }
            });

//  应用图标拖动
            $(".one ul .li").hammer().on("drag", function (e) {
                e.preventDefault();
                if ($(this).data("hold")) {
                    $(this).css("z-index", 111);
                    var posX = e.gesture.deltaX;
                    var posY = e.gesture.deltaY;
                    var x = +$(this).attr("x");
                    var y = +$(this).attr("y");
                    var L = x + posX;
                    var T = y + posY
                    /*
                     if (L > 3 * W)
                     L = 3 * W;
                     else if (L < 0)
                     L = 0;
                     if (T < 0)
                     T = 0;
                     else if (T > height)
                     T = height;
                     */
                    $(this).css("left", L + "px").css("top", T + "px");
                    var tempCss = {};
                    tempCss.left = $(this).css("left");
                    tempCss.left = +tempCss.left.substr(0, tempCss.left.length - 2);
                    tempCss.top = $(this).css("top");
                    tempCss.top = +tempCss.top.substr(0, tempCss.top.length - 2);
                    var disT = tempCss.top - (height * 0.75);
                    var disL = tempCss.left - (width / 2 - 60);
                    var disR = disT * disT + disL * disL;
                    if (disR < 2000) {
                        $(".del img").attr("src", "../../common/page/images/delete2.png");
                    } else {
                        $(".del img").attr("src", "../../common/page/images/delete.png");
                    }
                }
            });
            //  应用图标拖动 结束 ，计算图标位置
            $(".one ul .li").hammer().on("dragend", function (e) {
                if ($(this).data("hold")) {
                    //   console.log(e);
                    d3.selectAll("li").style({
                        "z-index": "10"
                    });
                    $(".one").css("border", "0px");
                    var render = $(this);
                    var temp = {};
                    temp.x = +$(this).attr("x");
                    temp.y = +$(this).attr("y");
                    var tempCss = {};
                    tempCss.left = $(this).css("left");
                    tempCss.left = +tempCss.left.substr(0, tempCss.left.length - 2);
                    tempCss.top = $(this).css("top");
                    tempCss.top = +tempCss.top.substr(0, tempCss.top.length - 2);
                    var disT = tempCss.top - (height * 0.75);
                    var disL = tempCss.left - (width / 2 - 60);
                    var disR = disT * disT + disL * disL;
                    //      console.log(tempCss.left, tempCss.top, disT, disL);
                    //if (disR < 2000) {
                    if($(".del img").attr("src").indexOf("delete2.png")>-1){
                        render.remove();
                        var key = +$(this).attr("data-key");
                        var id = $(this).attr("data-index");
                        one_just(temp, key);
                        Del_ajax(id, LeftTime);
                        return;
                    }
                    /*
                     else if (tempCss.left > 3 * W && LeftTime < 5) {
                     var key = +$(this).attr("data-key");
                     one_just(temp, key);
                     LeftTime++;
                     var temp = render;
                     render.remove();
                     $(".one ul").each(function (i) {
                     var left = d3.select(this).style("left");
                     left = +left.substr(0, left.length - 2);
                     $(this).animate({left: (left - width) + "px"}, 250, function () {
                     });
                     });

                     var len = $(".one .ul" + LeftTime + " .li").length;
                     $(".one .ul" + LeftTime).append(temp);
                     $(temp).attr("x", (len % 4) * W).attr("y", Math.floor(len / 4) * H + 20).attr("data-key", len);
                     temp.animate({
                     left: (len % 4) * W + "px",
                     top: (Math.floor(len / 4) * H) + 20 + "px"
                     }, 250, function () {
                     drag();
                     });
                     }
                     else if (tempCss.left < 0 && LeftTime > 1) {
                     var key = +$(this).attr("data-key");
                     one_just(temp, key);
                     LeftTime--;
                     var temp = render;
                     render.remove();
                     $(".one ul").each(function (i) {
                     var left = d3.select(this).style("left");
                     left = +left.substr(0, left.length - 2);
                     $(this).animate({left: (left + width) + "px"}, 250, function () {

                     });
                     });

                     var len = $(".one .ul" + LeftTime + " .li").length;
                     $(".one .ul" + LeftTime).append(temp);
                     $(temp).attr("x", (len % 4) * W).attr("y", Math.floor(len / 4) * H + 20).attr("data-key", len);
                     temp.animate({
                     left: (len % 4) * W + "px",
                     top: (Math.floor(len / 4) * H) + 20 + "px"
                     }, 250, function () {
                     //     drag();
                     });
                     } */

                    else {
                        var min = 10000000, minPos = 0;
                        //       console.log(tempCss);
                        for (var i = 0; i < $(".one .ul" + LeftTime + " .li").length; i++) {
                            var tx = +$(".one .ul" + LeftTime + " .li :eq(" + i + ")").attr("x");
                            var ty = +$(".one .ul" + LeftTime + " .li :eq(" + i + ")").attr("y");
                            if ((tempCss.top - ty) * (tempCss.top - ty) + (tempCss.left - tx) * (tempCss.left - tx) < min) {
                                min = (tempCss.top - ty) * (tempCss.top - ty) + (tempCss.left - tx) * (tempCss.left - tx);
                                minPos = +$(".one .ul" + LeftTime + " .li :eq(" + i + ")").attr("data-key");
                            }
                        }
                        var thisPos = +$(this).attr("data-key");
                        var minIdex = 0
                        for (var j = 0; j < $(".one .ul" + LeftTime + " .li").length; j++) {
                            if (+$(".one .ul" + LeftTime + " .li :eq(" + j + ")").attr("data-key") == minPos)
                                minIdex = j;
                        }
                        var thatPos = {};
                        thatPos.x = +$(".one .ul" + LeftTime + " .li :eq(" + minIdex + ")").attr("x");
                        thatPos.y = +$(".one .ul" + LeftTime + " .li :eq(" + minIdex + ")").attr("y");
                        //       console.log(minPos);
                        //         console.log(thatPos);
                        $(render).animate({left: thatPos.x + "px", top: thatPos.y + "px"}, 250, function () {
                            $(this).attr("x", thatPos.x).attr("y", thatPos.y).attr("data-key", minPos);
                        });
                        $(".one .ul" + LeftTime + " .li :eq(" + minIdex + ")").animate({left: temp.x + "px", top: temp.y + "px"}, 250, function () {
                            $(this).attr("x", temp.x).attr("y", temp.y).attr("data-key", thisPos);
                        });
                    }

                    d3.selectAll("li").style("z-index", 10);
                    d3.selectAll(".one ul li p span").transition().duration(250).style("-webkit-transform", "scale(1)");
                    d3.selectAll(".one ul li p img").transition().duration(250).style("-webkit-transform", "scale(1)");

                }
                $("li").data("hold", false);
                d3.selectAll("li").style("z-index", 10);
                d3.selectAll(".one ul li p span").transition().duration(250).style("-webkit-transform", "scale(1)");
                d3.selectAll(".one ul li p img").transition().duration(250).style("-webkit-transform", "scale(1)");
                JQajax();
            });
            $("p").on(touch_s, function () {
                $(this).css("background", "rgba(0,0,0,.3)");

            });
            $("p").on(touch_e, function () {
                $(this).css("background", "");
            });
            $(".one ul .li").on(touch_e, function () {
                d3.selectAll(".one ul li p span").transition().duration(250).style("-webkit-transform", "scale(1)");
                d3.selectAll(".one ul li p img").transition().duration(250).style("-webkit-transform", "scale(1)");
            });
            $(".one ul .li").on("click", function (e) {
                    // console.log(e);
                if ($(this).data("hold")) {
                    return;
                }
                else {
                    var url = $(this).data("url");
					var appVersion = $(this).attr("data-appVersion");
                    var href = location.href;
                    var len = href.lastIndexOf("/");
					//edit by lixuefang 20160509,将二期的应用统一在xgwgl的list页面渲染
					if(appVersion == 'oacloud'){
						 var userId=window.localStorage["userId"];
						 window.openViewB(href.substr(0, len - 4) + "xgwgl/list.html");
					}else if(appVersion == 'sw'){
						 if (url === "project"){
							 window.openViewB(href.substr(0, len - 4) + "sw/projectList.html");
						 }
					}else{
					   if (url === "qsbg" || url === "swfw" || url === "yyzx" || url === "ysyb" || url === "hygl" || url === "dcdb"|| url === "zfwj"|| url === "gzjb" || url === "swwj") {
							window.openViewB(href.substr(0, len - 4) + url + "/" + url + ".html?left=" + LeftTime);
							// window.openViewB("../" + url + "/" + url + ".html?left=" + LeftTime);
						}
						else if (url === "gzdt") {
							window.openViewB(href.substr(0, len - 4) + "zfgzdt/zfgzdt.html");
						}
					   else if(url==="无"){ //添加工作报告
						   window.openViewB(href.substr(0, len - 4) + "gzbg/gzbg.html")
					   }
						else {
							window.openViewB(href.substr(0, len - 4) + "ing/ing.html");
						}
					}


                }

            });
            $(".one ul .li").hammer().on("release", function () {

                $("p").css("background", "");

                if ($(this).data("hold")) {
                    var rend = d3.select(".one");
                    var temp = d3.select(this);
                    var key = $(this).data("key");
                    $(rend.node()).hammer().on("click", function (e) {
                        if (e.target.className === "li_1") {
                            $(temp.node()).data("hold", false);

                        }
                        else {
                            d3.selectAll(".one ul li p span").transition().duration(250).style("-webkit-transform", "scale(1)");
                            d3.selectAll(".one ul li p img").transition().duration(250).style("-webkit-transform", "scale(1)");

                            $(temp.node()).data("hold", false);
                        }

                    });
                }
                else {
                    d3.selectAll("li").style("z-index", 10);
                    d3.selectAll(".one ul li p span").transition().duration(250).style("-webkit-transform", "scale(1)");
                    d3.selectAll(".one ul li p img").transition().duration(250).style("-webkit-transform", "scale(1)");
                }

            });
         //   oneScroll.refresh();
        }

        // 删除图标
        function delappend() {
            var del = d3.select(".index_bg").append("div").classed("del", true).style({
                position: "absolute",
                "z-index": "9",
                top: height * 0.75 + "px",
                width: "40px",
                height: "60px",
                left: "50%",
                "margin-left": "-20px"

            });
            del.append("img").attr("src", "../../common/page/images/delete.png").style({
                width: "100%",
                height: "100%"
            });
        }

// 移动图标后 记录移动位置
        function one_just(temp, key) {
            $(".one .ul" + LeftTime + " .li").each(function (i) {
                if (+$(this).attr("data-key") > key) {
                    var key1 = +$(this).attr("data-key");
                    $(this).attr("data-key", key1 - 1);
                }
                if (+$(this).attr("y") > temp.y || (Math.abs(+$(this).attr("y") - temp.y) < 2 && +$(this).attr("x") > temp.x)) {

                    if ($(this).attr("x") == "0") {

                        $(this).animate({
                            left: (3 * W) + "px",
                            top: (+$(this).attr("y") - H) + "px"
                        }, 250, function () {
                            $(this).attr("x", 3 * W).attr("y", +$(this).attr("y") - H);

                        });
                    }
                    else {

                        $(this).animate({
                            left: +$(this).attr("x") - W + "px"

                        }, 250, function () {
                            $(this).attr("x", +$(this).attr("x") - W);

                        });
                    }
                }

            });
        }

// 让后台记录应用图标顺序
        function JQajax() {
            setTimeout(function () {
                d3.selectAll(".del").remove();
                //   var JQone = $(".one .ul" + LeftTime + " .li");
                var JQbtm = $(".index_btm .li");
                JQbtm.sort(function cmp(a, b) {
                    return (+$(a).attr("x1")) - (+$(b).attr("x1"));
                });

                var mbdesk = [];
                //       console.log(JQone);
                for (var i = 1; i <= 5; i++) {
                    mbdesk[i] = "";
                    var JQone = $(".one .ul" + i + " .li");

                    JQone.sort(function cmp(a, b) {
                        if (+$(a).attr("y") === +$(b).attr("y"))
                            return (+$(a).attr("x")) - (+$(b).attr("x"));
                        return  (+$(a).attr("y")) - (+$(b).attr("y"));
                    });
                    if (JQone.length) {
                        for (var j = 0; j < JQone.length - 1; j++) {
                            mbdesk[i] += $(JQone[j]).data("index") + ",";
                        }
                        mbdesk[i] += $(JQone[j]).data("index");
                    }
                }

                var config = {};


                config.mbdesk1 = mbdesk[1];
                config.mbdesk2 = mbdesk[2];
                config.mbdesk3 = mbdesk[3];
                config.mbdesk4 = mbdesk[4];
                config.mbdesk5 = mbdesk[5];

                config.mbdock = "";

                if (JQbtm.length) {
                    for (var j = 0; j < JQbtm.length - 1; j++) {
                        config.mbdock += $(JQbtm[j]).data("index") + ",";
                    }
                    config.mbdock += $(JQbtm[j]).data("index");
                }

                var url = serverURL + "cmcp/app/moveMyMBApp";
                console.log(config);
                var xtechAth=window.localStorage["xtechAth"];
                $.ajax({
                    url: url,
                    dataType: "json",
                    type: "POST",
                    beforeSend: function(xhr) {
                    	xhr.setRequestHeader("XTECH_ATH",xtechAth);
                    },
                    data: JSON.stringify(config),
                    contentType: "application/json",
                    success: function () {
                        var url = serverURL + "cmcp/app/findAllInstalledMBApps.json";
                        var xtechAth=window.localStorage["xtechAth"];
                        $.ajax({
                            url: url,
                            dataType: "text",
                            beforeSend: function(xhr) {
                            	xhr.setRequestHeader("XTECH_ATH",xtechAth);
                            },
                            success: function (r) {
                                if (typeof (r) == "string") {
                                    r = JSON.parse(r);
                                }

                                //   window.localStorage.Lcatch = JSON.stringify(r);
                            },
                            error: function (e) {
                                console.log("error");
                            }
                        });

                    },
                    error: function () {
                        console.log("error");

                    }
                });


            }, 300);
        }

        // 删除应用 ，提交后台  id ：应用id ，desk ：应用所在桌面标号
        function Del_ajax(id, desk) {
            d3.selectAll("li").transition().duration(250).style("-webkit-transform", "scale(1)");
            $(".del").animate({opacity: "0"}, 1000, function () {
                $(this).remove();
            });
            var url = serverURL + "cmcp/app/delApp?id=" + id + "&from=MB&mbdesk=" + desk;
            //    console.log(url);
            var xtechAth=window.localStorage["xtechAth"];
            $.ajax({
                url: url,
                type: "POST",
                beforeSend: function(xhr) {
                	xhr.setRequestHeader("XTECH_ATH",xtechAth);
                },
                success: function (dat) {
                    if (dat != "SUCCESS") {
                        Prompt("删除失败！", 500);
                        return;
                    }
                    var url = serverURL + "cmcp/app/findAllInstalledMBApps.json";
                    var xtechAth=window.localStorage["xtechAth"];
                    $.ajax({
                        url: url,
                        dataType: "text",
                        beforeSend: function(xhr) {
                        	xhr.setRequestHeader("XTECH_ATH",xtechAth);
                        },
                        success: function (r) {
                            if (typeof (r) == "string") {
                                r = JSON.parse(r);
                            }
                            window.localStorage.Lcatch = JSON.stringify(r);
                        },
                        error: function (e) {

                        }
                    });

                },
                error: function () {
                    Prompt("删除失败！", 500);

                }
            });

        }
    }


}